package com.enjoylearning.media.api;

import com.enjoylearning.base.model.RestResponse;
import com.enjoylearning.media.model.dto.UploadFileParamDto;
import com.enjoylearning.media.service.MediaFileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
public class BigFileController {

    @Autowired
    MediaFileService mediaFileService;

    @ApiOperation(value = "文件上传前检查文件")
    @PostMapping("/upload/checkfile")
    public RestResponse<Boolean> checkfile(
            @RequestParam("fileMd5") String fileMd5
    ) throws Exception {
        return mediaFileService.checkFile(fileMd5);
    }


    @ApiOperation(value = "分块文件上传前的检测")
    @PostMapping("/upload/checkchunk")
    public RestResponse<Boolean> checkchunk(@RequestParam("fileMd5") String fileMd5,
                                            @RequestParam("chunk") int chunk) throws Exception {
        return mediaFileService.checkChunk(fileMd5, chunk);
    }

    @ApiOperation(value = "上传分块文件")
    @PostMapping("/upload/uploadchunk")
    public RestResponse uploadchunk(@RequestParam("file") MultipartFile file,
                                    @RequestParam("fileMd5") String fileMd5,
                                    @RequestParam("chunk") int chunk) throws Exception {
        //获取文件
        File TempFile = File.createTempFile("md5", ".temp");
        file.transferTo(TempFile);

        Long companyId = 1L;
        //文件路径
        String absolutePath = TempFile.getAbsolutePath();
        RestResponse<Boolean> booleanRestResponse = mediaFileService.uploadChunk(fileMd5, chunk, absolutePath);
        TempFile.delete();
        return booleanRestResponse;
    }

    @ApiOperation(value = "合并文件")
    @PostMapping("/upload/mergechunks")
    public RestResponse mergechunks(@RequestParam("fileMd5") String fileMd5,
                                    @RequestParam("fileName") String fileName,
                                    @RequestParam("chunkTotal") int chunkTotal) throws Exception {
        Long companyId = 1L;
        UploadFileParamDto uploadFileParamDto = new UploadFileParamDto();
        uploadFileParamDto.setFileType("001002");
        uploadFileParamDto.setTags("课程视频");
        uploadFileParamDto.setRemark("");
        uploadFileParamDto.setFilename(fileName);
        return mediaFileService.mergechunks(companyId,fileMd5,chunkTotal,uploadFileParamDto);
    }


}
